﻿using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using EntityFramework6.Services.Data;
using EntityFramework6.Services.Services;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;

namespace Entityframework6.Tests
{
    [TestClass]
    public class Entityframework6ServiceTests
    {
        [TestMethod]
        public void Save_NewBook_Pass()
        {
            var mockDbSet = new Mock<DbSet<Book>>();
            var mockContext = new Mock<BookContext>();
            mockContext.Setup(m => m.Books).Returns(mockDbSet.Object);

            var service = new BookService(mockContext.Object);
            service.Save(new Book(){Name = "New book", Price = 12, ISBN = "ISBN"});

            mockDbSet.Verify(m => m.Add(It.IsAny<Book>()), Times.Once());
            mockContext.Verify(m => m.SaveChanges(), Times.Once()); 
        }

        [TestMethod]
        public void List_ReadBooks_Pass()
        {

            IQueryable<Book> data = new List<Book>()
            {
                new Book() {Name = "New book"},
                new Book() {Name = "New book 2"},
                new Book() {Name = "New book 3"}
            }.AsQueryable();
            var mockDbSet = new Mock<DbSet<Book>>();
            // NB: Setting up the enumberator on DBSet otherwise there will be error...
            mockDbSet.As<IQueryable<Book>>().Setup(m => m.GetEnumerator()).Returns(data.GetEnumerator());

            var mockContext = new Mock<BookContext>();
            mockContext.Setup(m => m.Books).Returns(mockDbSet.Object);

            var service = new BookService(mockContext.Object);
            var books = service.List();

            mockContext.Verify(m=> m.Books, Times.Once);
            Assert.AreEqual(3, books.Count);
        }
    }
}
